<template>
  <div class="createTicket">
    <div class="top">
      <p>
        设备名称：<span class="name">{{ info.name }}</span>
      </p>
      <p>
        安装位置：<span class="name">{{ info.installLocationName }}</span>
      </p>
    </div>
    <div class="bg">
      <div class="collapse_item">
        <van-form @failed="onFailed" @submit="onSubmit">
          <van-cell-group>
            <van-field
              required
              v-model="exceptionType"
              is-link
              readonly
              type="text"
              name="异常类型"
              label="异常类型"
              placeholder="异常类型"
              @click="handleSelect('exceptionType')"
              :rules="[{ required: true, message: '异常类型' }]"
            />
            <van-field
              required
              v-model="form.item"
              type="text"
              name="异常项目"
              label="异常项目"
              placeholder="异常项目"
              :rules="[{ required: true, message: '异常项目' }]"
            />
            <van-field
              required
              v-model="dispatchUserId"
              is-link
              readonly
              type="text"
              name="派工人员"
              label="派工人员"
              placeholder="派工人员"
              @click="handleSelect('dispatchUserId')"
              :rules="[{ required: true, message: '派工人员' }]"
            />
            <van-field
              required
              is-link
              readonly
              v-model="urgencyLevel"
              type="text"
              name="紧急程度"
              label="紧急程度"
              placeholder="紧急程度"
              @click="handleSelect('urgencyLevel')"
              :rules="[{ required: true, message: '紧急程度' }]"
            />

            <div>
              <p class="upload_img"><span class="bt">*</span> <span>处理时效</span></p>
              <div class="time_box">
                期望
                <div>
                  <van-button @click="handleMinus" icon="minus" plain size="small" />
                  <p class="val">{{ form.timeLimit }}</p>
                  <van-button @click="handlePlus" icon="plus" plain size="small" />
                </div>
                小时内
              </div>
            </div>
            <div>
              <p class="upload_img"><span class="bt">*</span> <span>现场图片</span></p>
              <van-uploader class="custom_uploader" v-model="fileList" multiple />
            </div>
            <van-field
              v-model="form.remark"
              class="custom_textarea"
              type="textarea"
              name="情况描述"
              label="情况描述"
              placeholder="情况描述"
              :rules="[{ required: false, message: '情况描述' }]"
              rows="4"
              autosize
              maxlength="200"
              show-word-limit
            />
          </van-cell-group>
          <div class="btns">
            <van-button block type="primary" style="width: 320px" native-type="submit">
              提交
            </van-button>
          </div>
        </van-form>
      </div>
    </div>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-picker
        :columns="columns[selectKey]"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
    <van-overlay :show="showOverlay" class-name="loading_overlay">
      <van-loading class="loading" type="spinner" color="#1989fa" />
    </van-overlay>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getInfo } from '@/api/equipmentLedger.js';
import { getDictOptions } from '@/utils/dic.js';
import { getUserAll } from '@/api/equipmentLedger.js';
import { formatData } from '@/utils/common.js';
import { urgencyLevelOptions } from '@/utils/options.js';
import { showNotify } from 'vant';
import { addOrder } from '@/api/workOrder.js';
const router = useRouter();
const route = useRoute();
const fileList = ref([]);
const form = reactive({
  exceptionType: '',
  remark: '',
  item: '',
  deviceId: route.params.deviceId,
  dispatchUserId: '',
  urgencyLevel: '',
  timeLimit: 0,
  photoIdList: [1],
});
const exceptionType = ref();
const dispatchUserId = ref();
const urgencyLevel = ref();
const showPicker = ref(false);
const showOverlay = ref(false);
const selectKey = ref('');
const info = ref({});
const columns = reactive({
  exceptionType: [],
  dispatchUserId: [],
  urgencyLevel: [...urgencyLevelOptions],
});

onMounted(async () => {
  if (!route.params.deviceId) {
    showNotify({ type: 'warning', message: '缺少设备id' });
    return;
  }
  showOverlay.value = true;
  const arr1 = await getDictOptions('exceptionType');
  columns.exceptionType = formatData(arr1) || [];
  await getPersons();
  await getDetail(route.params.deviceId);
  showOverlay.value = false;
});
const getPersons = async () => {
  // showOverlay.value = true;
  try {
    const res = await getUserAll();
    if (res.code == 200) {
      columns.dispatchUserId = formatData(res.data, 'name', 'id') || [];
    }
    showOverlay.value = false;
  } catch (error) {
    // showOverlay.value = false;
  }
};
function getDetail(deviceId) {
  // showOverlay.value = true;
  getInfo(deviceId)
    .then((res) => {
      if (res.code == 200) {
        info.value = res.data;
      }
    })
    .catch((err) => {
      showNotify({ type: 'warning', message: err.msg || '设备id异常' });
    })
    .finally(() => {
      // showOverlay.value = false;
    });
}

const onSubmit = (values) => {
  // showOverlay.value = true;
  addOrder(form)
    .then((res) => {
      if (res.code == 200) {
        showNotify({ type: 'success', message: '成功' });
        setTimeout(router.push({ path: '/ticket' }), 1000);
      }
    })
    .catch((err) => {
      showNotify({ type: 'warning', message: err.msg || '异常' });
    })
    .finally(() => {
      // showOverlay.value = false;
    });
};
const onFailed = (errorInfo) => {
  console.log('failed', errorInfo);
};
const handleMinus = (errorInfo) => {
  if (form.timeLimit > 0) {
    form.time--;
  }
};
const handlePlus = (errorInfo) => {
  form.timeLimit++;
};

const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false;

  switch (selectKey.value) {
    case 'exceptionType':
      exceptionType.value = selectedOptions[0]?.text;
      form.exceptionType = [selectedOptions[0]?.value];
      break;
    case 'dispatchUserId':
      dispatchUserId.value = selectedOptions[0]?.text;
      form.dispatchUserId = selectedOptions[0]?.value;
      break;
    case 'urgencyLevel':
      urgencyLevel.value = selectedOptions[0]?.text;
      form.urgencyLevel = selectedOptions[0]?.value;
      break;
  }
};
const handleSelect = (key) => {
  selectKey.value = key;
  showPicker.value = true;
};
</script>

<style lang="scss" scoped>
.createTicket {
  padding: 24px 0;
  height: calc(100vh - 100px);
  overflow-y: auto;
  .top {
    p {
      padding-left: 16px;
      width: 100%;
      height: 44px;
      line-height: 24px;
      font-weight: 400;
      font-size: 14px;
      color: #333333;
    }
    .name {
      display: inline-block;
      margin-left: 20%;
      width: 50%;
      color: #999999;
    }
  }

  .bg {
    // background: url('@/assets/images/bg2.png') no-repeat;
    background-size: 100% 100%;
    width: 100%;
  }
  .btns {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  .time_box {
    height: 50px;
    padding-left: 36px;
    display: flex;
    justify-content: start;
    align-items: center;
    gap: 24px 0;
    margin-bottom: 12px;
  }
  .time_box > div {
    margin: 0 24px;
    width: 120px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .custom_textarea {
    ::v-deep .van-field__value {
      padding: 10px 16px;
      background: #f8f8f8;
      border-radius: 2px 2px 2px 2px;
    }
  }
}
</style>
